package com.qf.openapi2204.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qf.openapi2204.common.mqbean.ApiTimeCostMqBean;
import lombok.SneakyThrows;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.util.Date;

@Component
public class TimeCostAfterFilter extends ZuulFilter {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 200;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @SneakyThrows
    @Override
    public Object run() throws ZuulException {

        //1. 取出起始时间
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        long start = (long) request.getAttribute("start-time");

        //2. 输出结束时间并计算时间查
        long end = System.currentTimeMillis();

        System.out.println("time used:"+(end-start));

        //3. 把接口的调用时长封装成一个消息对象，写入mq
        ApiTimeCostMqBean apiTimeCostMqBean = new ApiTimeCostMqBean();

        apiTimeCostMqBean.setApiName(request.getParameter("method"));
        apiTimeCostMqBean.setAppKey(request.getParameter("app_key"));
        apiTimeCostMqBean.setStart(new Date(start));
        apiTimeCostMqBean.setEnd(new Date(end));
        apiTimeCostMqBean.setTimecost(end-start);
        apiTimeCostMqBean.setRemoteIp(request.getRemoteAddr());
        apiTimeCostMqBean.setServerIp(InetAddress.getLocalHost().getHostAddress());

        rabbitTemplate.convertAndSend("","openapi-apitimecost-queue",apiTimeCostMqBean);

        return null;
    }
}
